<template>
  <div class="clue-container">
    <!-- 搜索筛选区域 -->
    <div class="search-filter">
      <div class="filter-row">
        <div class="filter-left">
          <el-input v-model="searchForm.name" placeholder="部门名称" clearable class="search-input" />
          <el-select v-model="searchForm.status" placeholder="部门状态" clearable class="search-select">
            <el-option label="请选择" value="" />
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </div>
        <div class="filter-right">
          <el-button type="primary" @click="handleSearch" class="search-btn">搜索</el-button>
          <el-button @click="handleClear" class="reset-btn">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showAddDialog" class="add-btn">添加部门</el-button>
    </div>

    <!-- 部门列表 -->
    <div class="clue-table-wrapper">
      <el-table 
        v-loading="loading"
        :data="paginatedDeptList" 
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" :width="idColumnWidth" />
        <el-table-column prop="name" label="部门名称" :width="contentColumnWidth" />
        <el-table-column prop="status" label="部门状态" :width="contentColumnWidth">
          <template #default="scope">
            <span :class="getStatusClass(scope.row.status)">{{ getStatusText(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" :width="contentColumnWidth">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="最后修改时间" :width="contentColumnWidth">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="contentColumnWidth">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="showDeleteDialog(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增部门对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增部门"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="部门名称：" prop="name">
          <el-input 
            v-model="addForm.name" 
            placeholder="请输入部门名称"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="部门状态：" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择">
            <el-option label="正常" value="normal"></el-option>
            <el-option label="停用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改部门对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改部门"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="部门名称：" prop="name">
          <el-input 
            v-model="editForm.name" 
            placeholder="请输入部门名称"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="部门状态：" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option label="正常" value="normal"></el-option>
            <el-option label="停用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="提示"
      width="300px"
      :close-on-click-modal="false"
    >
      <div class="text-center">您确认删除该部门吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 创建axios实例并添加请求拦截器
// 配置baseURL为'/api'，这样请求会经过vite的代理转发到后端
const api = axios.create({
  baseURL: '/api'
})

// 请求拦截器 - 添加token认证头
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.token = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应式数据
const loading = ref(false)
const deptList = ref([])
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 定义列宽度
const idColumnWidth = ref(80) // ID列的固定宽度
const contentColumnWidth = ref(0) // 其他列的宽度

// 监听窗口大小变化，动态调整列宽
const updateColumnWidth = () => {
  // 获取容器宽度
  const containerWidth = document.querySelector('.clue-container')?.offsetWidth || 1200
  // 减去内边距和边距
  const availableWidth = containerWidth - 40 // 减去左右padding 20px
  // ID列使用固定宽度，其他4列平分剩余宽度
  contentColumnWidth.value = Math.floor((availableWidth - idColumnWidth.value) / 4)
}

// 窗口大小变化监听的清理
onUnmounted(() => {
  window.removeEventListener('resize', updateColumnWidth)
})

// 对话框状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const currentDeleteId = ref(null)

// 表单引用
const addFormRef = ref(null)
const editFormRef = ref(null)

// 新增表单
const addForm = reactive({
  name: '',
  status: 1
})

// 修改表单
const editForm = reactive({
  id: '',
  name: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 10, message: '部门名称长度为2-10位', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择部门状态', trigger: 'change' }
  ]
}

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 加载部门列表
const loadDeptList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      name: searchForm.name,
      status: searchForm.status ? Number(searchForm.status) : undefined,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })
    
    // 调用后端API（注意：api实例已经配置了baseURL: '/api'，所以路径不需要再包含/api前缀）
    const response = await api.get('/depts', { params })
    
    if (response.data.code === 1) {
      deptList.value = response.data.data.rows
      pagination.total = response.data.data.total
    } else {
      ElMessage.error(response.data.msg || '获取部门列表失败')
      deptList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败，请稍后重试')
    deptList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 由于后端已经分页，直接使用deptList作为表格数据
const paginatedDeptList = computed(() => deptList.value)

// 搜索
const handleSearch = () => {
  // 重置页码
  pagination.currentPage = 1
  // 执行搜索逻辑
  loadDeptList()
}

// 清空
const handleClear = () => {
  // 清空搜索条件
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  // 重置页码
  pagination.currentPage = 1
  // 重新加载数据
  loadDeptList()
}

// 显示新增对话框
const showAddDialog = () => {
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = key === 'status' ? 1 : ''
  })
  // 显示对话框
  addDialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    // 调用根据ID查询部门的接口获取最新数据
    const response = await api.get(`/depts/${row.id}`)
    
    if (response.data.code === 1) {
      // 使用接口返回的数据填充编辑表单
      editForm.id = response.data.data.id
      editForm.name = response.data.data.name
      editForm.status = response.data.data.status
      editDialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取部门详情失败')
    }
  } catch (error) {
    console.error('获取部门详情失败:', error)
    ElMessage.error('获取部门详情失败，请稍后重试')
  }
}

// 显示删除对话框
const showDeleteDialog = (id) => {
  currentDeleteId.value = id
  deleteDialogVisible.value = true
}

// 添加部门
const handleAdd = () => {
  if (!addFormRef.value) return
  
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用后端API
        const response = await api.post('/depts', {
          name: addForm.name,
          status: Number(addForm.status)
        })
        
        if (response.data.code === 1) {
          addDialogVisible.value = false
          ElMessage.success('部门添加成功')
          loadDeptList()
        } else {
          ElMessage.error(response.data.msg || '添加部门失败')
        }
      } catch (error) {
        console.error('添加部门失败:', error)
        ElMessage.error('添加部门失败，请稍后重试')
      }
    }
  })
}

// 修改部门
const handleEdit = () => {
  if (!editFormRef.value) return
  
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用后端API
        const response = await api.put('/depts', {
          id: editForm.id,
          name: editForm.name,
          status: Number(editForm.status)
        })
        
        if (response.data.code === 1) {
          editDialogVisible.value = false
          ElMessage.success('部门修改成功')
          loadDeptList()
        } else {
          ElMessage.error(response.data.msg || '修改部门失败')
        }
      } catch (error) {
        console.error('修改部门失败:', error)
        ElMessage.error('修改部门失败，请稍后重试')
      }
    }
  })
}

// 删除部门
const handleDelete = async () => {
  ElMessageBox.confirm(
    '确定要删除该部门吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用后端API
      const response = await api.delete(`/depts/${currentDeleteId.value}`)
      
      if (response.data.code === 1) {
        deleteDialogVisible.value = false
        ElMessage.success('部门删除成功')
        loadDeptList()
      } else {
        ElMessage.error(response.data.msg || '删除部门失败')
      }
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error('删除部门失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadDeptList()
}

// 页码变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  loadDeptList()
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '正常',
    0: '停用'
  }
  return statusMap[status] || '未知'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    1: 'status-follow',
    0: 'status-fake'
  }
  return classMap[status] || ''
}

// 获取所有正常部门列表
const getAllActiveDepts = async () => {
  try {
    const response = await api.get('/api/depts/list')
    
    if (response.data.code === 1) {
      return response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取正常部门列表失败')
      return []
    }
  } catch (error) {
    console.error('获取正常部门列表失败:', error)
    ElMessage.error('获取正常部门列表失败，请稍后重试')
    return []
  }
}

// 页面加载时初始化数据和计算列宽
onMounted(() => {
  loadDeptList()
  updateColumnWidth()
  window.addEventListener('resize', updateColumnWidth)
})
</script>

<style scoped>
.clue-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
}

/* 搜索筛选区域 */
.search-filter {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-left,
  .filter-right {
    width: 100%;
    justify-content: stretch;
  }
  
  .filter-right {
    justify-content: center;
  }
}

.filter-left {
  display: flex;
  gap: 15px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-select {
  width: 220px;
}

/* 工具栏 */
.toolbar {
  display: flex;
  gap: 10px;
}

/* 表格样式 */
.clue-table-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

/* 表格内容和表头居中显示 */
.clue-table-wrapper :deep(.el-table th),
.clue-table-wrapper :deep(.el-table td) {
  text-align: center;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

/* 状态标签样式 */
.status-follow {
  color: #67c23a;
  font-weight: 500;
}

.status-fake {
  color: #f56c6c;
  font-weight: 500;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .filter-row {
    flex-wrap: wrap;
  }
  
  .search-input,
  .search-select {
    width: calc(50% - 10px);
    min-width: 200px;
  }
}

@media (max-width: 768px) {
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .toolbar {
    flex-wrap: wrap;
  }
}
</style>